//
//  MessagesViewController.m
//  Gabber
//
//  Created by 陆惠国 on 11-8-26.
//  Copyright 2011年 恒生聚源. All rights reserved.
//

#import "MessagesViewController.h"
#import "XMPPClient.h"

#import "Message.h"
#import "MessageCell.h"

@implementation MessagesViewController
@synthesize items = _items;
@synthesize badges = _badges;
@synthesize sendfaceArray=_sendfaceArray;
@synthesize receivefaceArray=_receivefaceArray;


@synthesize fetchedResultsController = _fetchedResultsController;

#pragma mark - Init/dealloc
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization

        self.title = @"未读消息";
        self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:@"消息" image:[UIImage imageNamed:@"chat"] tag:1] autorelease];    
        //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
//        UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:self.view.frame];
//        backgroundView.image=[UIImage imageNamed:@"Background"];
//        backgroundView.contentMode= UIViewContentModeCenter;
//        backgroundView.autoresizingMask =UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
//
//        
//        self.tableView.backgroundView = backgroundView; 
//        self.tableView.backgroundColor = [UIColor clearColor];
//        
//        [backgroundView release];
        
        
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleMessageReceived:) name: kMessageReceivedNotification object: nil]; 
        
        [self updateBadge];
        
        NSArray* receiveArr = [NSArray arrayWithObjects:@">:o",@":-[",@";-)",@"B-)",@":'(",@"]:)",@":-D",@":-)",@":^0",@":x",@";\\",@":-(",@":-p",@"?:|",@":0",@":|",@"(!)",@"(i)",@"(+)",@"(-)",@"(heart)",nil];
        
        NSArray*  sendArr = [NSArray arrayWithObjects:@"\uE416",@"\uE401",@"\uE405",@"\uE107",@"\uE411",@"\uE412",@"\uE415",@"\uE056",@"\uE057",@"\uE418",@"\uE410",@"\uE403",@"\uE409",@"\uE020",@"\uE40b",@"\uE40d",@"\uE021",@"\uE022",@"\uE41f",@"\uE00e",@"\uE421",nil];
        
        _receivefaceArray=[[NSMutableArray alloc]initWithArray:receiveArr];
        _sendfaceArray=[[NSMutableArray alloc]initWithArray:sendArr];
    
    }
    return self;
}

- (void)dealloc
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    _fetchedResultsController.delegate = nil;
    
    TT_RELEASE_SAFELY(_fetchedResultsController); 
    TT_RELEASE_SAFELY(_items); 
    TT_RELEASE_SAFELY(_badges); 
    TT_RELEASE_SAFELY(_receivefaceArray);
    TT_RELEASE_SAFELY(_sendfaceArray);
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
   
    [self reloadData];
	[super viewWillAppear:animated];
    


}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
    if (TTIsPad()) {
        return YES;
        
    } else {
        return interfaceOrientation == UIInterfaceOrientationPortrait;
    }
}


#pragma mark - NSFetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController
{
	if (_fetchedResultsController == nil)
	{
		NSManagedObjectContext *moc = [[XMPPClient sharedInstance] managedObjectContext_message];
		
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message"
		                                          inManagedObjectContext:moc];
		NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"jidStr" ascending:YES];
        NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:NO];


		
        
        NSPredicate *predicate=  [NSPredicate predicateWithFormat:@"streamBareJidStr == %@ AND read == %@ AND outbound == %@ ",
                                  [[[[XMPPClient sharedInstance] xmppStream]myJID] bare],[NSNumber numberWithBool:NO],[NSNumber numberWithBool:NO]];
        
        
        
		NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
		
		NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
		[fetchRequest setEntity:entity];
        [fetchRequest setPredicate:predicate];
		[fetchRequest setSortDescriptors:sortDescriptors];
		[fetchRequest setFetchBatchSize:10];
		
		_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:@"jidStr" cacheName:nil];
		[_fetchedResultsController setDelegate:self];
        NSError *error = nil;
        if (![[self fetchedResultsController] performFetch:&error])
        {
            DDLogWarn(@"Error performing fetch: %@", error);
        }         
        
		[sd1 release];
        [sd2 release];
		[fetchRequest release];
	}
    return _fetchedResultsController;
}

- (void)reloadData {
	DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    @try {
        
        self.items  = [NSMutableArray array];
        self.badges = [NSMutableDictionary dictionary];
        
        for (id <NSFetchedResultsSectionInfo> sectionInfo in [self.fetchedResultsController sections]) {
            Message* msg =[sectionInfo.objects objectAtIndex:0];
            [self.items addObject:msg];
            [self.badges setObject: [NSString stringWithFormat:@"%d", [[sectionInfo objects] count]] forKey:msg.jidStr];
        }
        [self.items sortUsingSelector:@selector(timestampCompare:)]; 
        
        [[self tableView] reloadData];
        [self updateBadge];
        
        
    }
    @catch (NSException *exception) {
        DDLogError(@"Exception: %e", exception);
    }
    @finally {
        
    }
    
}

#pragma mark - NSFetchedResultsControllerDelegate

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self reloadData];
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"MessageCell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil)
	{
		
        cell = [[[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:CellIdentifier] autorelease];
	}
	
    [self configureCell:cell forIndexPath:indexPath];
	
	return cell;
}

- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath 
{
    if ([cell isKindOfClass:[MessageCell class]]){
        MessageCell* messageCell =  (MessageCell*)cell;
        
        Message *message = [self messageForRowAtIndexPath:indexPath];
        
        for (int i=0; i<_receivefaceArray.count; i++) {
            
            NSString*  receivestr = [_receivefaceArray objectAtIndex:i];
            NSRange suffixRange=[message.content rangeOfString:receivestr];
            
            if (!(suffixRange.location == NSNotFound)) {
                NSString* sendstr=[_sendfaceArray objectAtIndex:i];
                message.content =[message.content stringByReplacingOccurrencesOfString:receivestr withString:sendstr];
            }
        }


        messageCell.badgeValue = [self.badges objectForKey:message.jidStr];        
        
        messageCell.message = message;

    }
}

- (Message *)messageForRowAtIndexPath:(NSIndexPath*)indexPath
{  
    return [self.items objectAtIndex: indexPath.row];
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    Message *message = [self messageForRowAtIndexPath:indexPath];
    NSString* url= [NSString stringWithFormat:@"gabber://chat/%@", message.jidStr];
    TTOpenURLFromView(url, tableView);
}

#pragma mark - kMessageReceivedNotification

- (void)handleMessageReceived:(NSNotification *)notification
{
    [self updateBadge];

}
      
- (void)updateBadge
{
    NSInteger count = [[self.fetchedResultsController fetchedObjects] count];
    if (count >0){
        [UIApplication sharedApplication].applicationIconBadgeNumber = count;
        self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d" ,count];
    }else{
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        self.tabBarItem.badgeValue = nil;  
    }   
}

@end
